package com.cheung.leetcode.str;

import java.util.Stack;

public class LC20 {

    public static boolean isValid(String s) {

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // 如果当前元素是左括号，压入栈
            if (c == '{' || c == '(' || c == '[') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                } else {
                    // 栈顶元素和当前元素是否成对
                    Character p = stack.peek();
                    boolean is = (p == '(' && c == ')') || (p == '{' && c == '}') || (p == '[' && c == ']');
                    if (is) {
                        stack.pop();
                    } else {
                        return false;
                    }
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isValid("()[]{}"));
    }
}
